#pragma once
#include <iostream>
#include <string>
#include <errno.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define PATH "./fifo"
#define MODE 0666
using namespace std;
class Fifo
{
public:
    Fifo(const string &path = PATH) : _path(path)
    {
        umask(0000);
        int n = mkfifo(PATH, MODE); // 创建管道
        if (n == 0)
        {
            cout << "make fifo success!" << endl;
        }
        else
        {
            cerr << "make fifo failed! " << "errno is " << errno << " " << strerror(errno) << endl;
            exit(0);
        }
    }
    ~Fifo()
    {
        int n = unlink(PATH);
        if (n == 0)
        {
            cout << "remove file fifo success!" << endl;
        }
        else
        {
            cerr << "remove file fifo failed! " << "errno is " << errno << " " << strerror(errno) << endl;
        }
    }

private:
    string _path;
};

class Sync
{
public:
    Sync(int rfd = -1, int wfd = -1) : _rfd(rfd), _wfd(wfd)
    {}
    ~Sync() {}
    void OpenReadOrDie()
    {
        _rfd = open(PATH, O_RDONLY);
        if (_rfd < -1) 
        {
            cerr << "open file fifo failed! " << "errno: " << errno << ", errstring: " << strerror(errno) << endl;
            exit(1);
        }
         cout << "OpenRead sunccess" << endl;
    }
    void OpenWriteOrDie()
    {
         _wfd = open(PATH, O_WRONLY);
        if (_wfd == -1)
        {
            cerr << "open file fifo failed! " << "errno is " << errno << " " << strerror(errno) << endl;
            exit(1);
        }
    }

    bool Wait()
    {
        bool ret = true;
        int a;
        int n = read(_rfd, &a, sizeof(int));    //管道没有数据就阻塞
        if (n == sizeof(int))
        {
            cout << "server wakeup..." << endl;
        }
        else if (n == 0) ret = false;   //客户端退出
        else ret = false;
        return ret;
    }

    void Wakeup()
    {
        int a = 1;
        int n = write(_wfd, &a, sizeof(int));
        if (n == sizeof(int))
        {
            cout << "wake up server..." << endl;
        }
    }
private:
    int _rfd;
    int _wfd;
};